package com.fubowen.lepton.ui.container.children.bookmark

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.commit
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.fubowen.lepton.R
import com.fubowen.lepton.databinding.FragmentBookmarkGroupPreviewBinding
import com.fubowen.lepton.helper.DBHelper
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class BookmarkGroupPreviewFragment : Fragment() {

    private lateinit var binding: FragmentBookmarkGroupPreviewBinding
    private val args: BookmarkGroupPreviewFragmentArgs by navArgs()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentBookmarkGroupPreviewBinding.inflate(inflater, container, false)
        binding.bookmarkGroupBack.setOnClickListener { goBackImpl() }
        binding.bookmarkGroupTitle.text = args.title
        goBack()
        childFragmentManager.commit {
            BookmarkFragment().apply {
                arguments = bundleOf("id" to args.id, "title" to args.title)
                add(R.id.bookmark_group_content, this)
            }
        }
        binding.bookmarkGroupDelete.setOnClickListener {
            CoroutineScope(Dispatchers.Main).launch {
                val bookmark = DBHelper.db.bookmarkDao().get(args.id)
                DBHelper.db.bookmarkDao().put(bookmark.parentId, args.id)
                DBHelper.db.bookmarkDao().del(bookmark)
                goBackImpl()
            }
        }
        return binding.root
    }

    private fun goBack() {
        val onBackCallback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                goBackImpl()
                isEnabled = false
            }
        }
        requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, onBackCallback)
    }

    private fun goBackImpl() = findNavController().navigateUp()
}